// 封装购物车模块
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'


export const useCartStore = defineStore('cart', () => {
    // 定义购物测列表
    const cartList = ref([])
    // 定义添加
    const addCart = async (goods) => {
        // 添加购物测操作
        // 加过count+1
        // 没有直接push
        const item = cartList.value.find((item) => goods.skuID === item.skuID === item.skuID)
        if (item) {
            // 找到了
            item.count++
        } else {
            cartList.value.push(goods)
        }
    }


    // 删除购物车
    const delCart = (skuID) => {
        // 找到要删除项的下标值
        const idx = cartList.value.findIndex((item) => skuID === item.skuID)
        cartList.value.splice(idx, 1)
    }

    // 单选功能
    const singleCheck = (skuId, selected) => {
        // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }


    // 计算属性
    // 总的数量
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    // 总价
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
    
    return {
        cartList,
        allCount,
        allPrice,
        addCart,
        delCart,
        singleCheck,
    }
})